/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MessageDialog.java
 *
 * Created on Mar 30, 2011, 8:58:45 PM
 */

package org.libarae.client;

import java.net.SocketTimeoutException;
import java.util.Calendar;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Message;
import org.libarae.communication.common.MessageThread;
import org.libarae.communication.request.GetThreadMessagesRequest;
import org.libarae.communication.request.SendMessageRequest;
import org.libarae.communication.response.GetThreadMessageResponse;
import org.libarae.communication.response.Response;

/**
 *
 * @author Casey, Ben
 */
@SuppressWarnings("serial")
public class MessageDialog extends javax.swing.JFrame {

    private MessageThread mMessageThread;
    private Vector<Message> mThreadMessages;
    
    /** Creates new form MessageDialog */
    public MessageDialog(MessageThread mMessageThread) {
        this.mMessageThread = mMessageThread;
        initComponents();

        lblFrom.setText(mMessageThread.getUserName1());
        lblSubject.setText(mMessageThread.getSubject());


        GetThreadMessagesRequest r = new GetThreadMessagesRequest();
        r.setMessageThread(mMessageThread);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            System.err.println("Server could not be reached.");
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            GetThreadMessageResponse gtmr = (GetThreadMessageResponse)response;

            mThreadMessages = gtmr.getMessages();

            DefaultListModel model = new DefaultListModel();

            if(mThreadMessages.size() == 0)
            {
                model.add(0, "<html><br>No messages found.<br></html>");
            }
            else
            {
                for(Message m : mThreadMessages)
                {
                    Calendar time = Calendar.getInstance();
                    time.setTimeInMillis(m.getTime());

                    String message = m.getMessageText();

                    message = message.replaceAll("\n", "<br>");

                    model.addElement("<html><div width=\""+(lstMessages.getWidth()-20)+"\">Sent at "+String.format("%tT", time) + "<br>" + message + "</div><br></html>");
                }
            }

            lstMessages.setModel(model);
        }

        if(mThreadMessages.firstElement().isNeedsApproval())
        {
            btnReply.setEnabled(false);
            btnAccept.setEnabled(true);
            btnDeny.setEnabled(true);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblFromLabel = new javax.swing.JLabel();
        lblSubjectLabel = new javax.swing.JLabel();
        lblBodyLabel = new javax.swing.JLabel();
        btnReply = new javax.swing.JButton();
        lblFrom = new javax.swing.JLabel();
        lblSubject = new javax.swing.JLabel();
        scrMessages = new javax.swing.JScrollPane();
        lstMessages = new javax.swing.JList();
        scrPersonalMessage = new javax.swing.JScrollPane();
        txtPersonalMessage = new javax.swing.JTextPane();
        btnAccept = new javax.swing.JButton();
        btnDeny = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Message");
        setIconImage(new ImageIcon(getClass().getResource("/res/icon.png")).getImage());
        setLocationByPlatform(true);

        lblFromLabel.setText("Started by:");

        lblSubjectLabel.setText("Subject: ");

        lblBodyLabel.setText("Body:");

        btnReply.setText("Reply");
        btnReply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReplyActionPerformed(evt);
            }
        });

        lblFrom.setText(" ");

        lblSubject.setText(" ");

        lstMessages.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lstMessages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstMessages.setVisibleRowCount(-1);
        scrMessages.setViewportView(lstMessages);

        scrPersonalMessage.setViewportView(txtPersonalMessage);

        btnAccept.setText("Accept");
        btnAccept.setEnabled(false);
        btnAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcceptActionPerformed(evt);
            }
        });

        btnDeny.setText("Deny");
        btnDeny.setEnabled(false);
        btnDeny.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDenyActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(scrMessages, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                    .addComponent(scrPersonalMessage, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btnReply)
                        .addGap(18, 18, 18)
                        .addComponent(btnAccept)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDeny)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 108, Short.MAX_VALUE)
                        .addComponent(btnCancel))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblSubjectLabel)
                            .addComponent(lblBodyLabel)
                            .addComponent(lblFromLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblSubject)
                            .addComponent(lblFrom))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFromLabel)
                    .addComponent(lblFrom))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSubjectLabel)
                    .addComponent(lblSubject))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblBodyLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrMessages, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrPersonalMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnReply)
                    .addComponent(btnAccept)
                    .addComponent(btnDeny)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnReplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReplyActionPerformed
        SendMessageRequest r = new SendMessageRequest();
        r.setAction(SendMessageRequest.APPEND_MESSAGE);

        Message m = new Message();
        m.setToUser(mMessageThread.getUser1());
        m.setMessageText(txtPersonalMessage.getText());
        m.setThreadId(mMessageThread.getThreadId());

        r.setMessage(m);
        r.setMessageThread(mMessageThread);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            //TODO: Fix this.
            System.err.println("Error connecting to server");
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            this.dispose();
        }

        //TODO: Handle failure.
    }//GEN-LAST:event_btnReplyActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcceptActionPerformed
        SendMessageRequest r = new SendMessageRequest();
        r.setAction(SendMessageRequest.RESPOND_ACCEPT);

        Message m = new Message();
        m.setToUser(mMessageThread.getUser1());

        String message = txtPersonalMessage.getText();

        message = message.replaceAll("\n", "<br>");

        m.setMessageText("Your request was accepted.<br><br>" + message);
        
        m.setThreadId(mMessageThread.getThreadId());

        r.setMessage(m);
        r.setMessageThread(mMessageThread);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            //TODO: Fix this.
            System.err.println("Error connecting to server");
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            this.dispose();
        }

        //TODO: Handle failure.
    }//GEN-LAST:event_btnAcceptActionPerformed

    private void btnDenyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDenyActionPerformed
        SendMessageRequest r = new SendMessageRequest();
        r.setAction(SendMessageRequest.RESPOND_DENY);

        Message m = new Message();
        m.setToUser(mMessageThread.getUser1());

        String message = txtPersonalMessage.getText();

        message = message.replaceAll("\n", "<br>");

        m.setMessageText("Your request was denied.<br><br>" + message);

        m.setThreadId(mMessageThread.getThreadId());

        r.setMessage(m);
        r.setMessageThread(mMessageThread);

        Response response = null;

        try {
            response = ClientInterface.sendRequest(r);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            //TODO: Fix this.
            System.err.println("Error connecting to server");
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            this.dispose();
        }

        //TODO: Handle failure.
    }//GEN-LAST:event_btnDenyActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MessageDialog(new MessageThread()).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAccept;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnDeny;
    private javax.swing.JButton btnReply;
    private javax.swing.JLabel lblBodyLabel;
    private javax.swing.JLabel lblFrom;
    private javax.swing.JLabel lblFromLabel;
    private javax.swing.JLabel lblSubject;
    private javax.swing.JLabel lblSubjectLabel;
    private javax.swing.JList lstMessages;
    private javax.swing.JScrollPane scrMessages;
    private javax.swing.JScrollPane scrPersonalMessage;
    private javax.swing.JTextPane txtPersonalMessage;
    // End of variables declaration//GEN-END:variables

}
